package com.orangelife.service.propFeeInvoice.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.orangelife.common.MybaitsGenericDaoSubLogic;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.cerHouseholder.ICerHouseholderService;
import com.orangelife.service.propFeeInvoice.IPropFeeInvoiceService;
import com.orangelife.service.propFeeInvoice.model.PropFeeInvoiceDto;
import com.orangelife.service.propFeeInvoiceLink.IPropFeeInvoiceLinkService;
import com.orangelife.service.propFeeInvoiceLink.model.PropFeeInvoiceLinkDto;
import com.orangelife.service.propFeeOffsetInfo.IPropFeeOffsetInfoService;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.setting.constant.TypeConst;
import com.orangelife.utils.IdUtil;
import com.orangelife.utils.JSONHelper;
import com.orangelife.utils.StringUtils;

/*****************************************************************
 * Copyright(C) ORANGELIFE Corporation CodeConst.BIS_CODE_68001015. All Rights
 * Reserved.
 *****************************************************************/
/*
 * ============================================================== 功能名
 * PropFeeInvoice类的 service层的增删改查
 * 
 * @author @author zhr
 * 
 * @version 1.1.0
 * 
 * @date 2016-12-20 21:17:06
 * ==============================================================
 */
@Service("propFeeInvoiceService")
public class PropFeeInvoiceServiceImpl extends MybaitsGenericDaoSubLogic
		implements IPropFeeInvoiceService {
	private static Logger logger = Logger
			.getLogger(PropFeeInvoiceServiceImpl.class);

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		PropFeeInvoiceServiceImpl.logger = logger;
	}

	@Resource(name = "cerHouseholderService")
	private ICerHouseholderService cerHouseholderService;
	@Resource(name = "propFeeInvoiceLinkService")
	private IPropFeeInvoiceLinkService propFeeInvoiceLinkService;
	@Resource(name = "propFeeOffsetInfoService")
	private IPropFeeOffsetInfoService propFeeOffsetInfoService;

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int addPropFeeInvoice(PropFeeInvoiceDto propFeeInvoice)
			throws AppBizException {

		Assert.notNull(propFeeInvoice);
		/************************************************
		 * 判断输入参数的长度以及是否能为空
		 ************************************************/

		if (!StringUtils.isBlank(propFeeInvoice.getInvoiceNum())) {
			if (propFeeInvoice.getInvoiceNum().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "收据编码长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getInvoiceType())) {
			if (propFeeInvoice.getInvoiceType().length() > 1) {
				throw new AppBizException(CodeConst.SYS_CODE_1002,
						"收据类型(1预存款，2其他费用，3转存，4冲抵)长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getStatus())) {
			if (propFeeInvoice.getStatus().length() > 1) {
				throw new AppBizException(CodeConst.SYS_CODE_1002,
						"状态(1有效，2报废)长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getHouseInfo())) {
			if (propFeeInvoice.getHouseInfo().length() > 128) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "房屋信息长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getDrawer())) {
			if (propFeeInvoice.getDrawer().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "开票人长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getAmountInWords())) {
			if (propFeeInvoice.getAmountInWords().length() > 64) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "大写金额长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getAmount())) {
			if (propFeeInvoice.getAmount().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "金额长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getCreateuser())) {
			if (propFeeInvoice.getCreateuser().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "创建者长度超出");
			}
		}

		propFeeInvoice.setInvoiceID(IdUtil.getuuId());
		propFeeInvoice.setItemStat(TypeConst.FLAG_ON);
		propFeeInvoice.setTscreate(new Date());
		propFeeInvoice.setTsedit(new Date());
		return this.getSqlSession().insert(
				"PropFeeInvoiceMapper.insertSelective", propFeeInvoice);
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int editPropFeeInvoice(PropFeeInvoiceDto propFeeInvoice)
			throws AppBizException {

		Assert.notNull(propFeeInvoice);
		/************************************************
		 * 判断输入参数的长度以及是否能为空
		 ************************************************/
		if (StringUtils.isBlank(propFeeInvoice.getInvoiceID())) {
			throw new AppBizException(CodeConst.SYS_CODE_1001, "ID不可为空");
		}
		PropFeeInvoiceDto oldPropFeeInvoice = this
				.findPropFeeInvoiceByID(propFeeInvoice.getInvoiceID());

		if (!StringUtils.isBlank(propFeeInvoice.getInvoiceNum())) {
			if (propFeeInvoice.getInvoiceNum().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "收据编码长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getInvoiceType())) {
			if (propFeeInvoice.getInvoiceType().length() > 1) {
				throw new AppBizException(CodeConst.SYS_CODE_1002,
						"收据类型(1预存款，2其他费用，3转存，4冲抵)长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getStatus())) {
			if (propFeeInvoice.getStatus().length() > 1) {
				throw new AppBizException(CodeConst.SYS_CODE_1002,
						"状态(1有效，2报废)长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getHouseInfo())) {
			if (propFeeInvoice.getHouseInfo().length() > 128) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "房屋信息长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getDrawer())) {
			if (propFeeInvoice.getDrawer().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "开票人长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getAmountInWords())) {
			if (propFeeInvoice.getAmountInWords().length() > 64) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "大写金额长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getAmount())) {
			if (propFeeInvoice.getAmount().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "金额长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeInvoice.getCreateuser())) {
			if (propFeeInvoice.getCreateuser().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "创建者长度超出");
			}
		}

		if (oldPropFeeInvoice == null) {
			throw new AppBizException(CodeConst.BIS_CODE_68001,
					InfoConst.BIS_INFO_68001);
		}
		propFeeInvoice.setTsedit(new Date());
		return this.getSqlSession().update(
				"PropFeeInvoiceMapper.updateByPrimaryKeySelective",
				propFeeInvoice);
	}

	@Override
	public PropFeeInvoiceDto findPropFeeInvoiceByID(String propFeeInvoiceID)
			throws AppBizException {
		if (StringUtils.isBlank(propFeeInvoiceID)) {

			throw new AppBizException(CodeConst.SYS_CODE_1001, "ID不可为空");
		}

		/************************************************
		 * 判断实体是否存在
		 ************************************************/
		PropFeeInvoiceDto oldPropFeeInvoice = this.getSqlSession().selectOne(
				"PropFeeInvoiceSearchMapper.selectByPrimaryKey",
				propFeeInvoiceID);
		if (oldPropFeeInvoice == null) {
			throw new AppBizException(CodeConst.BIS_CODE_68001,
					InfoConst.BIS_INFO_68001);
		}

		if (TypeConst.FLAG_OFF.equals(oldPropFeeInvoice.getItemStat())) {

			throw new AppBizException(CodeConst.BIS_CODE_68001,
					InfoConst.BIS_INFO_68001);
		}
		return oldPropFeeInvoice;
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int deletePropFeeInvoiceByLogic(String propFeeInvoiceID)
			throws AppBizException {

		if (StringUtils.isBlank(propFeeInvoiceID)) {
			throw new AppBizException(CodeConst.SYS_CODE_1001, "ID不可为空");
		}
		/************************************************
		 * 判断实体是否存在
		 ************************************************/
		PropFeeInvoiceDto oldPropFeeInvoice = this
				.findPropFeeInvoiceByID(propFeeInvoiceID);

		oldPropFeeInvoice.setItemStat(TypeConst.FLAG_OFF);
		oldPropFeeInvoice.setTsedit(new Date());
		return this.getSqlSession().update(
				"PropFeeInvoiceMapper.updateByPrimaryKeySelective",
				oldPropFeeInvoice);
	}

	@Override
	public List<Map<String, Object>> findPropFeeInvoiceByPage(
			String invoiceType, String apartmentID, String tsCreate,
			String search, int pageNo, int pageSize) throws AppBizException {

		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("invoiceType", invoiceType);
		map.put("apartmentID", apartmentID);
		map.put("tsCreate", tsCreate);
		map.put("search", search);
		PageHelper.startPage(pageNo, pageSize);
		List<Map<String, Object>> list = this.getSqlSession().selectList(
				"PropFeeInvoiceSearchMapper.findAllPropFeeInvoice", map);
		return list;
	}

	@Override
	public List<PropFeeInvoiceDto> getPropFeeInvoiceByPage(String tsCreate,
			String search, int pageNo, int pageSize) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tsCreate", tsCreate);
		map.put("search", search);
		PageHelper.startPage(pageNo, pageSize);
		List<PropFeeInvoiceDto> list = this.getSqlSession().selectList(
				"PropFeeInvoiceSearchMapper.getAllPropFeeInvoiceDto", map);
		return list;
	}

	@Override
	public List<Map<String, Object>> selectPropFeeInvoiceByRelevantID(
			String invoiceID, String invoiceType, String status, String pmID,
			String commID, String apartmentID) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("invoiceID", invoiceID);
		map.put("invoiceType", invoiceType);
		map.put("status", status);
		map.put("pmID", pmID);
		map.put("commID", commID);
		map.put("apartmentID", apartmentID);

		List<Map<String, Object>> list = this
				.getSqlSession()
				.selectList(
						"PropFeeInvoiceSearchMapper.selectPropFeeInvoiceDtoyRelevantID",
						map);
		return list;
	}

	@Override
	public List<PropFeeInvoiceDto> findPropFeeInvoiceByRelevantID(
			String invoiceID, String invoiceType, String status, String pmID,
			String commID, String apartmentID) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("invoiceID", invoiceID);
		map.put("invoiceType", invoiceType);
		map.put("status", status);
		map.put("pmID", pmID);
		map.put("commID", commID);
		map.put("apartmentID", apartmentID);

		List<PropFeeInvoiceDto> list = this.getSqlSession().selectList(
				"PropFeeInvoiceSearchMapper.findPropFeeInvoiceDtoByRelevantID",
				map);
		return list;
	}

	@Override
	public List<PropFeeInvoiceDto> bauthfindPropFeeInvoice(
			List<String> propFeeInvoiceIDs) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		List<PropFeeInvoiceDto> list = this.getSqlSession().selectList(
				"PropFeeInvoiceSearchMapper.batchFindPropFeeInvoice",
				propFeeInvoiceIDs);
		return list;
	}

	@Override
	public List<Map<String, Object>> bauthfindPropFeeInvoiceByMap(
			Map<String, Object> propFeeInvoice) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		List<Map<String, Object>> list = this.getSqlSession().selectList(
				"PropFeeInvoiceSearchMapper.batchFindPropFeeInvoiceByMap",
				propFeeInvoice);
		return list;
	}

	@Override
	public void clearCache() throws AppBizException {
		System.out.println("清除缓存成功");
	}

	@Override
	public List<Map<String, Object>> getDetailInvTree(String feeTypeID,
			String apartmentID, String feeDate) throws AppBizException {

		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("feeTypeID", feeTypeID);
		map.put("apartmentID", apartmentID);
		map.put("feeDate", feeDate);

		List<String> feeDates = propFeeOffsetInfoService
				.getOffFeeDate(apartmentID);
		map.put("feeDates", feeDates);
		List<Map<String, Object>> list = this.getSqlSession().selectList(
				"PropFeeInvoiceSearchMapper.getDetailInvTree", map);
		return list;
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int addPropFeeInvoices(PropFeeInvoiceDto propFeeReceipt)
			throws AppBizException {
		Map<String, Object> map = new HashMap<String, Object>();
		if (propFeeReceipt.getReceiptLinkIDs() == null
				|| propFeeReceipt.getReceiptLinkIDs().size() <= 0) {
			throw new AppBizException(2, "亲，关联信息");
		}
		if (StringUtils.isBlank(propFeeReceipt.getInvoiceType())) {
			throw new AppBizException(2, "亲，票据类型");
		}
		if (StringUtils.isBlank(propFeeReceipt.getCommID())) {
			throw new AppBizException(2, "亲，小区信息");
		}
		if (StringUtils.isBlank(propFeeReceipt.getApartmentID())) {
			throw new AppBizException(2, "亲，房屋信息");
		}
		if (StringUtils.isBlank(propFeeReceipt.getInvoiceNum())) {
			throw new AppBizException(2, "亲，收据编码");
		}
		if (StringUtils.isBlank(propFeeReceipt.getAmount())) {
			throw new AppBizException(2, "亲，金额");
		}
		if (StringUtils.isBlank(propFeeReceipt.getAmountInWords())) {
			throw new AppBizException(2, "亲，大写金额");
		}
		if (!StringUtils.isBlank(propFeeReceipt.getApartmentID())) {
			Map<String, Object> propFeeComm = cerHouseholderService
					.getHouseInfo(propFeeReceipt.getApartmentID());
			StringBuffer houseInfo = new StringBuffer();
			houseInfo.append(propFeeComm.get("buildingName") + "-");
			if (propFeeComm.get("unitName") != null) {
				houseInfo.append(propFeeComm.get("unitName")).append("-");
			}
			houseInfo.append(propFeeComm.get("apartmentNum"));

			propFeeReceipt.setHouseInfo(houseInfo.toString());
			Map<String, Object> fInfo = JSONHelper.jsonToMap(propFeeReceipt
					.getContent());
			fInfo.put(
					"ownerName",
					propFeeComm.get("ownerName") != null ? propFeeComm
							.get("ownerName") : "");
			fInfo.put(
					"feeArea",
					propFeeComm.get("feeArea") != null ? propFeeComm.get(
							"feeArea").toString() : "0.00");
			propFeeReceipt.setContent(JSONObject.toJSONString(fInfo));
		}

		propFeeReceipt.setStatus("1");

		propFeeReceipt.setReceiptTime(new Date());
		int n = this.addPropFeeInvoice(propFeeReceipt);
		List<PropFeeInvoiceLinkDto> propFeeReceiptLinkDtos = new ArrayList<PropFeeInvoiceLinkDto>();
		if (n > 0) {
			for (int i = 0; i < propFeeReceipt.getReceiptLinkIDs().size(); i++) {
				if (!StringUtils.isBlank(propFeeReceipt.getReceiptLinkIDs()
						.get(i))) {
					List<PropFeeInvoiceLinkDto> propFeeReceiptLins = propFeeInvoiceLinkService
							.findPropFeeInvoiceLinkByRelevantID(null, null,
									propFeeReceipt.getInvoiceType(),
									propFeeReceipt.getReceiptLinkIDs().get(i));
					if (propFeeReceiptLins != null
							&& propFeeReceiptLins.size() > 0) {
						throw new AppBizException(2, "亲，该信息已经操作过");
					}
					PropFeeInvoiceLinkDto propFeeReceiptLinkDto = new PropFeeInvoiceLinkDto();
					propFeeReceiptLinkDto.setItemStat("1");
					propFeeReceiptLinkDto.setLinkID(propFeeReceipt
							.getReceiptLinkIDs().get(i));
					propFeeReceiptLinkDto.setInvoiceID(propFeeReceipt
							.getInvoiceID());

					propFeeReceiptLinkDto.setInvoiceLinkID(IdUtil.getuuId());
					propFeeReceiptLinkDto.setTscreate(new Date());
					propFeeReceiptLinkDto.setType(propFeeReceipt
							.getInvoiceType());
					propFeeReceiptLinkDtos.add(propFeeReceiptLinkDto);

				}

			}

			if (propFeeReceiptLinkDtos != null
					&& propFeeReceiptLinkDtos.size() > 0) {
				return propFeeInvoiceLinkService
						.addPropFeeInvoiceLink(propFeeReceiptLinkDtos);
			}

		}
		return n;

	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int nullifyReceipt(PropFeeInvoiceDto propFeeReceipt)
			throws AppBizException {
		PropFeeInvoiceDto oldFeeReceiptDto = this
				.findPropFeeInvoiceByID(propFeeReceipt.getInvoiceID());
		propFeeReceipt.setStatus("2");
		this.editPropFeeInvoice(propFeeReceipt);

		List<PropFeeInvoiceLinkDto> propFeeReceiptLinkDtos = propFeeInvoiceLinkService
				.findPropFeeInvoiceLinkByRelevantID(null,
						oldFeeReceiptDto.getInvoiceID(), null,
						oldFeeReceiptDto.getInvoiceType());

		List<String> linkIDs = new ArrayList<String>();
		for (PropFeeInvoiceLinkDto propFeeInvoiceLinkDto : propFeeReceiptLinkDtos) {
			linkIDs.add(propFeeInvoiceLinkDto.getInvoiceLinkID());
		}

		if (linkIDs != null && linkIDs.size() > 0) {
			return this.getSqlSession().update(
					"PropFeeInvoiceLinkBauthMapper.bauthDeleteLg", linkIDs);
		}
		return 0;

	}
}